package com.robot;

import iqq.im.QQActionListener;
import iqq.im.QQException;
import iqq.im.QQNotifyListener;
import iqq.im.WebQQClient;
import iqq.im.actor.QQActor;
import iqq.im.actor.QQActorDispatcher;
import iqq.im.actor.SwingActorDispatcher;
import iqq.im.bean.QQGroup;
import iqq.im.bean.QQMsg;
import iqq.im.bean.content.FontItem;
import iqq.im.bean.content.TextItem;
import iqq.im.event.QQActionEvent;
import iqq.im.event.QQActionEvent.Type;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import javax.imageio.ImageIO;

import com.robot.core.Config;
import com.robot.core.Context;
import com.robot.core.Source;
import com.robot.ui.LoginFrame;
import com.robot.ui.MainFrame;
import com.robot.ui.QQFrame;

public  class RobotClient extends WebQQClient implements Context {
	private Map<QQFrame.Type, QQFrame> frames;
	private Source source;
	private Config config;
	private QQActorDispatcher swActor;

	public RobotClient(String username, String password,
			QQNotifyListener notifyListener, QQActorDispatcher actorDispatcher) {
		super(username,password,notifyListener,actorDispatcher);		
		this.source = new Source();
		this.config = new Config();
		this.swActor = new SwingActorDispatcher();
		this.frames = new HashMap<QQFrame.Type,QQFrame>();
		frames.put(QQFrame.Type.LOGIN, new LoginFrame());
		frames.put(QQFrame.Type.MAIN, new MainFrame());
		init();
	}
	
	
	public void checkRcode(){
		this.checkQRCode(new QQActionListener() {
            @Override
            public void onActionEvent(QQActionEvent event) {
                System.out.println("checkQRCode " + event);
                switch (event.getType()) {
                    case EVT_OK:
                        // 扫描通过,登录成功
                    	// 到这里就算是登录成功了	
    					frames.get(QQFrame.Type.LOGIN).setVisible(false);
    					frames.get(QQFrame.Type.MAIN).setVisible(true);					
    					getGroupList(new QQActionListener() {
    						public void onActionEvent(QQActionEvent event) {
    							if (event.getType() == Type.EVT_OK) {
    								for (QQGroup g : getGroupList()) {
    									System.out.println(g);
    									getGroupInfo(g, null);
    									System.out.println("加载 : " + g.getName());
    								}
    							} else if (event.getType() == Type.EVT_ERROR) {
    								System.err.println(event.getType()+"  groupList");
    							}
    						}						
    					});                
    					//获取好友列表
                    	getBuddyList(null);
                    	try {Thread.sleep(5000);} catch (InterruptedException e) {}
    					beginPollMsg();		
    					beginPublicNotices();    				
                        break;
                    case EVT_ERROR:
                        QQException ex = (QQException) (event.getTarget());
                        QQException.QQErrorCode code = ex.getError();
                        switch (code) {
                            // 二维码有效,等待用户扫描
                            // 二维码已经扫描,等用户允许登录
                            case QRCODE_OK:
                            case QRCODE_AUTH:
                                try {
                                    Thread.sleep(3000);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                                // 继续检查二维码状态
                                checkQRCode(this);
                                break;
                        }
                        break;
                }
            }
        });
	}


	
	private void beginPublicNotices() {
		final Timer timer = new Timer();
		timer.schedule(new TimerTask() {
			public void run() {
				String msg = source.getNotice(System.currentTimeMillis());	 
				if(msg!=null){
					for(QQGroup g:getGroupList()){
						QQMsg qMsg = new QQMsg();
						qMsg.setGroup(g);
						qMsg.addContentItem(new TextItem(msg));
						qMsg.addContentItem(new FontItem());
						replyMsg(qMsg);
					}									
				}
			}
		}, 60000,60000);	
	}

	/**
	 * 回复消息
	 */
	public void replyMsg(final QQMsg msg) {
		sendMsg(msg, new QQActionListener() {			
			@Override
			public void onActionEvent(QQActionEvent event) {
				if(event.getType()==QQActionEvent.Type.EVT_OK){
					((MainFrame)frames.get(QQFrame.Type.MAIN))
						.showMsg(config.get("robotname")+"："+msg.getText(), Color.RED);
				}
			}
		});
		
	}
	/**
	 *GUI显示消息
	 */
	public void showMsg(String msg,Color color){
		((MainFrame)frames.get(QQFrame.Type.MAIN)).showMsg(msg,color);
	}
	
	public void init() {
		for(QQFrame.Type key:frames.keySet()){
			try {
				frames.get(key).init(this);
			} catch (QQException e) {
			}
		}
		showRecode();		
	}
	
	private void showRecode() {
		this.getQRcode(new QQActionListener() {
            @Override
            public void onActionEvent(QQActionEvent event) {
                if (event.getType() == QQActionEvent.Type.EVT_OK) {
                    try {
                        BufferedImage verify = (BufferedImage) event.getTarget();
                        ImageIO.write(verify, "png", new File("qrcode.png"));
                        System.out.println("请扫描在项目根目录下qrcode.png图片");
                        ((LoginFrame)frames.get(QQFrame.Type.LOGIN)).showView(verify);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    System.out.println("获取二维码失败");
                }
            }
        });
		checkRcode();
	}

	@Override
	public Source getSource() {
		// TODO Auto-generated method stub
		return this.source;
	}
	@Override
	public Config getConfig() {
		// TODO Auto-generated method stub
		return this.config;
	}
	
	@Override
	public void pushSwActor(QQActor actor) {
		swActor.pushActor(actor);
	}

	@Override
	public QQFrame getFrame(com.robot.ui.QQFrame.Type type) {
		return frames.get(type);
	}

	@Override
	public void publishNotice(long time, String msg) {
		this.source.putNotice(time, msg);
	}

	@Override
	public void exit() {
		System.exit(0);
	}


	
}
